#include <stdio.h>

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution
{
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
    {
        int add = 0;
        ListNode *dummyHead = new ListNode(-1);
        ListNode *cur = dummyHead;
        while (l1 && l2)
        {
            int num = l1->val + l2->val + add;
            add = num / 10;
            cur->next = new ListNode(num % 10);
            cur = cur->next;
            l1 = l1->next;
            l2 = l2->next;
        }

        while (l1)
        { 
            if (add)   
            {
                int num = l1->val + add;
                cur->next = new ListNode(num % 10);
                add = num / 10;
                l1 = l1->next;
                cur = cur->next;
            }
            else
            {
                cur->next = l1;
                break;
            }
        }

        while (l2)
        {
           if (add) 
           {
               int num = l2->val + add;
               cur->next = new ListNode(num % 10);
               add = num / 10;
               l2 = l2->next;
               cur = cur->next;
           }
           else
           {
               cur->next = l2;
               break;
           }
        }

        if (add)
        {
            cur->next = new ListNode(add);
        }
        return dummyHead->next;
    }
};